package com.example.softwareconfigurationcoursedesign;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserService {
    public List<User> getUserListFromDatabase() {
        // 连接数据库，执行查询操作，获取用户列表数据
        // 假设使用JDBC来访问数据库

        // 假设数据库表名为users，包含id、phone_number、name、password等字段
//        String sql = "SELECT uid, phone_number, name, password FROM users";
        String sql = "SELECT * FROM users";

        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/course_design", "root", "123456");
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {

            List<User> userList = new ArrayList<>();

            while (resultSet.next()) {
                int userId = resultSet.getInt("uid");
                String phoneNumber = resultSet.getString("phone_number");
                String name = resultSet.getString("name");
                String password = resultSet.getString("password");
                User user = new User(userId, phoneNumber, name, password);
                userList.add(user);
            }

            return userList;

        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }

        return Collections.emptyList();
    }

//    public void addUserToDatabase(User user) {
//        try (Connection connection = getConnection();
//             PreparedStatement statement = connection.prepareStatement(
//                     "INSERT INTO users (name, phone_number, password) VALUES (?, ?, ?)")) {
//
//            statement.setString(1, user.getName());
//            statement.setString(2, user.getPhoneNumber());
//            statement.setString(3, user.getPassword());
//
//            statement.executeUpdate();
//        } catch (SQLException e) {
//            e.printStackTrace(System.err);
//        }
//    }
}
